import { reqGetUserCode, reqUserRegister, reqUserLogin,reqUserInfo, reqLogOut  } from "@/api";

const state = {
  code: '', //存储数据
  token:localStorage.getItem('TOKEN'),//token,用户登录成功以后唯一标识(服务器用来区分用户身份的)
  nickName:''//用户个人信息之用户名
};

const mutations = {
  getUserCode(state, code) {
    state.code = code;
  },
  SET_TOKEN(state,token){
    state.token = token;
  },
  SET_USERINFO(state,nickName){
    state.nickName = nickName;
  },
  LOGOUT(state){
    //情况vuex里面用户名字
    state.nickName = '';
    //清除vuex的token数据
    state.token = '';
     //本地存储token数据清空
    localStorage.removeItem('TOKEN');
  }
};
const actions = {
  async getUserCode({ commit, state, dispatch, getters }, phone) {
    //向服务器发请求,将用户的手机号码携带给服务器
    //让服务器把验证码推送到用户手机当中
    //正常工作的时候,书写到这里就可以啦！！！！正常情况vuex不需要存储状态码
    //需要注意:咱们的后台老师并没有将验证码推送给用户手机上面(省钱)
    let result = await reqGetUserCode(phone);
    if (result.code == 200) {
      commit("getUserCode", result.data);
      return "ok";
    } else {
      return Promise.reject(new Error(result.message));
    }
  },
  //用户注册
  async userRegister({ commit, dispatch, state, getter }, data) {
    let result = await reqUserRegister(data);
    //注册成功
    if (result.code == 200) {
      return "ok";
    } else {
      return Promise.reject(new Error(result.message));
    }
  },
  //此action：是整个项目最重要一个action函数
  async userLogin({ commit, state, dispatch, getters }, data) {
    let result = await reqUserLogin(data);
    if(result.code == 200){
      commit('SET_TOKEN',result.data.token);
      localStorage.setItem('TOKEN',result.data.token);//当你第一次偶遇token,静悄悄的把持久化存储一下！！！
      return 'ok';
    }else{
      return Promise.reject(new Error(result.message));
    }
  },
   //获取用户信息
   async getUserInfo({commit,state,dispatch,getters}) {
    let result = await reqUserInfo();
    console.log(result);
    if(result.code == 200){
      commit('SET_USERINFO',result.data.nickName);
      return 'ok';
    }else{
      return Promise.reject(new Error(result.message))
    }
   },
    //退出登录
    //不允许在actions直接修改state数据
    async logout({commit,state,dispatch,getters}){
      let result = await reqLogOut();
      //退出登录成功
      if(result.code == 200){
        commit('LOGOUT');
        return 'ok';
      }else{
        return Promise.reject(new Error(result.message));
      }
    }
};

export default {
  state,
  mutations,
  actions,
};
